package login

import (
	"data/config"
	"data/view"
	"public/message"
	"public/mycache"
	"public/myhttp"
	"public/tools"
	"strconv"
	"time"
)

//登录获取token
func GetAccessTokenByUser(username, password, times string) (mess LoginToken_s) {
	if len(username) == 0 || len(password) == 0 || len(times) == 0 {
		mess.MessageBody = message.GetErrorMsg(message.ParameterInvalid)
		// mess.State = message.GetErrorMsg(message.ParameterInvalid).State
		// mess.Code = message.GetErrorMsg(message.ParameterInvalid).Code
		// mess.Error = message.GetErrorMsg(message.ParameterInvalid).Error
		return
	}
	token_type := config.GetTokenType()
	appid, appsecret := config.GetAppInfo()
	original := appid + username + password + times + appsecret
	token := tools.Md5Encoder(original)

	parm := make(map[string]string)
	parm["appid"] = appid
	parm["token"] = token
	parm["token_type"] = token_type
	parm["password"] = password
	parm["username"] = username
	parm["time"] = times

	myhttp.SendPost(parm, &mess, config.GetLoginUrl())
	if mess.State {
		//成功
		var tmp view.UserCacheBody
		tmp.Access_token = mess.Data.Access_token
		tmp.User_name = username
		tmp.Expire_time, _ = strconv.Atoi(mess.Data.Expire_time)

		//保存缓存
		cache := mycache.OnGetCache("oauth2")
		cache.Add(tmp.Access_token, &tmp, time.Duration(tmp.Expire_time)*time.Second)
		//------------------end
	}
	return

}

//登录获取token 非用户密码登录
func GetAccessTokenByUserNpwd(username, times string) (mess LoginToken_s) {
	if len(username) == 0 || len(times) == 0 {
		mess.MessageBody = message.GetErrorMsg(message.ParameterInvalid)
		// mess.State = message.GetErrorMsg(message.ParameterInvalid).State
		// mess.Code = message.GetErrorMsg(message.ParameterInvalid).Code
		// mess.Error = message.GetErrorMsg(message.ParameterInvalid).Error
		return
	}
	token_type := config.GetTokenType()
	appid, appsecret := config.GetAppInfo()
	original := appid + username + times + appsecret
	token := tools.Md5Encoder(original)

	parm := make(map[string]string)
	parm["appid"] = appid
	parm["token"] = token
	parm["token_type"] = token_type
	parm["username"] = username
	parm["time"] = times

	myhttp.SendPost(parm, &mess, config.GetLoginNoPwdUrl())
	if mess.State {
		//成功
		var tmp view.UserCacheBody
		tmp.Access_token = mess.Data.Access_token
		tmp.User_name = username
		tmp.Expire_time, _ = strconv.Atoi(mess.Data.Expire_time)

		//保存缓存
		cache := mycache.OnGetCache("oauth2")
		cache.Add(tmp.Access_token, &tmp, time.Duration(tmp.Expire_time)*time.Second)
		//------------------end
	}
	return

}
